package alipay.openplatform.edu.campus.jiuye.api.controller.user;

import alipay.openplatform.edu.campus.jiuye.api.utils.ContextUtils;
import alipay.openplatform.edu.campus.jiuye.common.enums.ResultCode;
import alipay.openplatform.edu.campus.jiuye.common.utils.ObjectUtils;
import alipay.openplatform.edu.campus.jiuye.model.po.UserTopicInfoPO;
import alipay.openplatform.edu.campus.jiuye.model.vo.TopicInfoVO;
import alipay.openplatform.edu.campus.jiuye.model.vo.UserBaseInfo;
import alipay.openplatform.edu.campus.jiuye.model.vo.UserTopicVO;
import alipay.openplatform.edu.campus.jiuye.service.dao.ApiResult;
import alipay.openplatform.edu.campus.jiuye.service.iservice.message.IMessageService;
import alipay.openplatform.edu.campus.jiuye.service.iservice.topic.ITopicDetailInfoService;
import alipay.openplatform.edu.campus.jiuye.service.iservice.user.IUserInfoService;
import alipay.openplatform.edu.campus.jiuye.service.iservice.user.IUserTopicInfoService;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/jiuye/api")
public class UserTopicInfoController {
    private static final Logger logger = LoggerFactory.getLogger(UserTopicInfoController.class);
    @Autowired
    private IUserTopicInfoService userTopicInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private ITopicDetailInfoService topicDetailInfoService;

    @Autowired
    HttpServletRequest request;

    /**
     * @param params 参数名
     * @param result 期望结果
     * @return
     */
    private static String resultStr(String params, String result) {
        params = params.trim();
        if (params.equals("null") || params.equals(""))
            return result;
        return params;
    }

    /**
     * 我要报名、收藏、取消收藏
     *
     * @param topicId
     * @param state
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendTopic", method = RequestMethod.POST)
    public ApiResult sendTopic(@RequestParam(required = false) String id, @RequestParam Integer topicId, @RequestParam Integer state, @RequestParam String topicType
            , @RequestParam(value = "schoolId", required = false, defaultValue = "0") String school_id, @RequestParam(value = "schoolName", required = false, defaultValue = "未知") String schoolName,
                               @RequestParam(value = "cityId", required = false, defaultValue = "0") String city_id, @RequestParam(value = "cityName", required = false, defaultValue = "未知") String cityName
    ) {
        String userId = ContextUtils.getUserId(request);
 //       String userId = "2088302167243547";
        logger.info("UserTopicInfoController|sendTopic|从Session中获取的userId={}", userId);

        String schoolId = resultStr(school_id, "0");
        String school_name = resultStr(schoolName, "未知");
        String cityId = resultStr(city_id, "0");
        String city_name = resultStr(cityName, "未知");

//        UserTopicInfoPO userTopicInfoPO = new UserTopicInfoPO();
//        userTopicInfoPO.setUserId(userId);
//        userTopicInfoPO.setTopicId(topicId);
//        userTopicInfoPO.setCreatetime(new Date());
//        userTopicInfoPO.setState(state);
//        userTopicInfoPO.setIfDel(Boolean.FALSE);
//        userTopicInfoPO.setSchoolId(schoolId);
//        userTopicInfoPO.setSchoolName(school_name);
//        userTopicInfoPO.setCityId(cityId);
//        userTopicInfoPO.setCityName(city_name);

        Map map = new HashMap();
        map.put("state", state);

        int result = 0;
        Map params = new HashMap();
        params.put("userId", userId);
        params.put("topicId", topicId);
        params.put("cityId", cityId);
        params.put("schoolId", schoolId);
        params.put("topicType", topicType);

        UserTopicInfoPO res = userTopicInfoService.selectIfExist(params);

        params.put("state", state);

        if (ObjectUtils.isNotNull(res) && ObjectUtils.isNotNull(res.getId())) {
            result = userTopicInfoService.updateTopic(params);
            map.put("id", res.getId());
        } else {
            UserTopicVO userTopicInfoVo = new UserTopicVO();
            userTopicInfoVo.setState(state);
            userTopicInfoVo.setTopicId(topicId);
            userTopicInfoVo.setUserId(userId);
            userTopicInfoVo.setCityId(cityId);
            userTopicInfoVo.setCityName(city_name);
            userTopicInfoVo.setSchoolId(schoolId);
            userTopicInfoVo.setSchoolName(school_name);
            userTopicInfoVo.setCreatetime(new Date());
            userTopicInfoVo.setIfDel(Boolean.FALSE);
            try {
                result = userTopicInfoService.sendTopic(userTopicInfoVo);
                map.put("id", result);
            } catch (Exception e) {
                return ApiResult.build("500", "系统异常");
            }
        }

        if (result > 0) {
            //报名,发送短信
            if (state == 1) {
                TopicInfoVO topicInfoVO = topicDetailInfoService.selectDetailInfoByTopicID(topicId);
                String start = new DateTime(topicInfoVO.getStarttime()).toString("yyyy-MM-dd");
                String now = new DateTime(new Date()).toString("yyyy-MM-dd");
                if (start.equals(now)) {
                    sendMessage(topicId, userId, topicInfoVO);
                }
            }
            return ApiResult.buildSuccess("0", "操作成功!", map);
        }
        return ApiResult.build("-1", "操作失败!");
    }

    /**
     * 发送短信
     *
     * @param topicId
     * @param userId
     */
    private void sendMessage(Integer topicId, String userId, TopicInfoVO topicInfoVO) {
        try {
            UserBaseInfo userBaseInfo = userInfoService.getUserInfoByUserId(userId);

            StringBuilder content = new StringBuilder();
            content.append("你已报名的").append(topicInfoVO.getTopicTitle())
                    .append("于").append(new DateTime(topicInfoVO.getStarttime()).toString("yyyy-MM-dd HH:mm")).append("召开，请准时参加。");

            for (int i = 0; i < 3; i++) {
                int res = userTopicInfoService.querySmsIfSend(userId, topicId);
                //未发送短信的
                if (res > 0) {
                    if (ObjectUtils.isNotNull(userBaseInfo.getMobile())) {
                        boolean sms = messageService.sendSms(userBaseInfo.getMobile(), content.toString());
                        //短信发送成功
                        if (sms) {
                            int updateres = userTopicInfoService.updateIfSMS(userId, topicId);
                            if (updateres > 0) {
                                logger.info("我要报名|短信发送成功、更新ifsms成功|手机:{}" + userBaseInfo.getMobile());
                                break;
                            } else {
                                logger.info("我要报名|短信发送成功、更新ifsms失败|手机:{}" + userBaseInfo.getMobile());
                                continue;
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            logger.error("操作失败,{}", e.getMessage());
        }
    }

    /**
     * 分页获取用户收藏的主题的列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/getMyTopicPage")
    @ResponseBody
    public ApiResult getMyTopicByPage(HttpServletRequest request) {
        logger.info("分页获取用户收藏的主题的列表|UserTopicInfoController|getMyTopicByPage|params:No");
        //4. 返回分页数据
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String userId = ContextUtils.getUserId(request);
            //String userId = "2088012199249492";


            logger.info("UserTopicInfoController|getMyTopicByPage|从Session中获取的userId={}", userId);
            result = userTopicInfoService.getMyTopicByPage(userId);
        } catch (Exception e) {
            logger.error("分页获取用户收藏的主题的列表|UserTopicInfoController|getMyTopicByPage|params:message={}", e);
            return ApiResult.build(ResultCode.GET_USER_TOPIC.getCode(), ResultCode.GET_USER_TOPIC.getName());
        }
        return ApiResult.buildSuccess(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName(), result);

    }
}